package dao

import (
	"github.com/jinzhu/gorm"
	"pojo/model"
	"pojo/form"
	"bytes"
)

/*
 * 客户数据库访问对象
 */
type UserDao struct {
	db *gorm.DB
}

/*
 * 构造新的客户需要传入数据库的对象
 */
func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{
		db: db,
	}
}

/*
 * 保存客户信息
 */
func (this *UserDao) InsertUser(user *model.User) (int64, error) {
	// 插入
	result := this.db.Save(user)
	return result.RowsAffected, result.Error
}

/*
 * 根据客户id查询单个客户信息
 */
func (this *UserDao) FindUser(id uint64) (*model.User, error) {
	user := &model.User{}
	result := this.db.Find(user, "id = ?", id)
	return user, result.Error
}

// 分页查询客户信息
func (this *UserDao) List(query *form.UserPageQueryForm) ([] *model.User, error) {

	params := make([]interface{}, 0)

	buf := new(bytes.Buffer)
	buf.WriteString(" 1 = 1 ")

	if len(query.Name) > 0 {
		buf.WriteString(" and name like ? ")
		params = append(params, query.Name)
	}

	if len(query.Phone) > 0 {
		buf.WriteString(" and phone like ? ")
		params = append(params, query.Phone)
	}

	users := make([] *model.User, 0)

	offset := (query.Page - 1) * query.Limit

	result := this.db.Where(buf.String(), params...).Offset(offset).Limit(query.Limit).Find(&users)

	return users, result.Error
}

// 统计客户信息
func (this *UserDao) Count(query *form.UserPageQueryForm) (uint64, error) {

	var total uint64

	params := make([]interface{}, 0)

	buf := new(bytes.Buffer)
	buf.WriteString(" 1 = 1 ")

	if len(query.Name) > 0 {
		buf.WriteString(" and name like ? ")
		params = append(params, query.Name+"%")
	}

	if len(query.Phone) > 0 {
		buf.WriteString(" and phone like ? ")
		params = append(params, query.Phone+"%")
	}

	result := this.db.Model(model.User{}).Where(buf.String(), params...).Count(&total)

	return total, result.Error
}

/*
 * 根据客户手机号查询单个客户信息
 */
func (this *UserDao) GetUserOneByPhone(phone string) (*model.User, error) {
	user := &model.User{}
	result := this.db.Find(user, "phone = ?", phone)
	return user, result.Error
}

/*
 * 根据客户id删除单个客户信息
 */
func (this *UserDao) DeleteUser(id uint64) (error) {

	return this.db.Delete(model.User{}, "id = ?", id).Error
}

/*
 * 修改客户信息
 */
func (this *UserDao) UpdateUserOne(user *model.User, id uint) (int64, error) {
	result := this.db.Model(&user).Where("id = ?", id).Update(user)
	return result.RowsAffected, result.Error
}
